package net.towee.server.factories;

import javax.inject.Inject;

import net.towee.model.account.AccountIdentity;
import net.towee.model.discussion.Discussion;
import net.towee.model.discussion.DiscussionFactory;
import net.towee.model.discussion.DiscussionSubject;
import net.towee.model.discussion.Message;
import net.towee.model.discussion.impl.DiscussionImpl;
import net.towee.model.discussion.impl.MessageImpl;
import net.towee.model.repo.AttachmentIdentity;
import net.towee.model.repo.DocumentIdentity;
import net.towee.server.persistence.AccountStore;
import net.towee.server.persistence.DiscussionStore;
import net.towee.shared.exceptions.PersistenceException;

import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Preconditions;
import com.mycila.event.internal.guava.base.Strings;

/**
 * This factory implementation create discussions and messages
 * 
 * @author c58
 */
public class DiscussionFactoryImpl implements DiscussionFactory {
	private static final Logger LOG = LoggerFactory.getLogger(DiscussionFactoryImpl.class);
	private final AccountStore accountStore;
	private final DiscussionStore discStore;

	@Inject
	public DiscussionFactoryImpl(AccountStore accountStore, DiscussionStore discStore) {
		this.accountStore = accountStore;
		this.discStore = discStore;
	}

	@Override
	public Discussion createDiscussion() {
		return new DiscussionImpl();
	}

	@Override
	public Message createMessage(String authorId, String text, String id, DiscussionSubject subject) {
		Preconditions.checkArgument( !Strings.isNullOrEmpty(text) );
		Preconditions.checkArgument( !Strings.isNullOrEmpty(id) );
		Preconditions.checkArgument( !Strings.isNullOrEmpty(authorId) );
		
		try {
			Message mess = new MessageImpl(accountStore.getAccountIdentity(authorId), text,
					new ObjectId().toString());
			
			discStore.addMessage(id, subject, mess);
			return mess;
		} catch (PersistenceException e) {
			LOG.error("Cant find account \""+authorId+"\" while creating message");
		}
		
		return null;
	}

}